﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Reflection.Emit;

namespace BasePlatformNet
{
	class CDxfInOutClass
	{
		[DllImport("kernel32.dll")]
		static extern IntPtr LoadLibrary(string lpFileName);
		
		[DllImport("kernel32.dll")]
		static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
		
		[DllImport("kernel32.dll")]
		static extern bool FreeLibrary(IntPtr hModule);

		[DllImport("kernel32.dll")]
		public static extern uint GetLastError();

		private IntPtr hModule = IntPtr.Zero;
		public IntPtr farProc = IntPtr.Zero;

		private delegate int ParseDXF(int id, string str1, byte[] data, string str2);
		
		string path = null;
		
		public CDxfInOutClass()
		{
			path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
			path = path.Substring(0, path.LastIndexOf("\\"));
		}
		
		// 加载 DLL
		public bool LoadDxfDll()
		{
			string pathfile = path + "\\" + "dxf32.dll";
			
			hModule = LoadLibrary(pathfile);
			if (hModule == IntPtr.Zero)
			{
				return false;
			}
			
			farProc = GetProcAddress(hModule, "parseDXF");
			if (farProc == IntPtr.Zero)
			{
				return false;
			}
			
			return true;
		}
		
		// 卸载 DLL
		public bool FreeDxfDll()
		{
			if (hModule != IntPtr.Zero)
			{
				FreeLibrary(hModule);
				return true;
			}
			
			return false;
		}
		
		// 将 dxf 文件解析为 bin 文件
		public bool GetDxfData(string srcfile)
		{
			bool loadflg = LoadDxfDll();
			if (loadflg == false)
			{
				return false;
			}

			ParseDXF parsedxf = (ParseDXF)Marshal.GetDelegateForFunctionPointer(farProc, typeof(ParseDXF));
			
			string outfile = path + "\\" + "dxfParse.bin";
			byte[] data = new byte[10];
			parsedxf(3, srcfile, data, outfile);

			bool freedllflg = FreeDxfDll();
			if (freedllflg == false)
			{
				return false;
			}
			
			return true;
		}
	}
}
